package uit.minito.timduongxebuyt;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import uit.minito.database.HistoryDBAdapter;
import uit.minito.database.HistoryModel;
import uit.minito.model.MyData;
import uit.minito.model.MyPoint;
import uit.minito.quickaction.ActionItem;
import uit.minito.quickaction.QuickAction;
import uit.minito.quickaction.QuickAction.OnActionItemClickListener;
import uit.minito.suggestion.SuggestionModel;
import uit.minito.views.CircleButton;
import uit.minito.views.CustomZoomControls;
import uit.minito.views.InputLayout;
import uit.minito.views.MainMenu;
import uit.minito.views.MyUtilities;
import uit.minito.views.OnCustomZoomControlsListener;
import uit.minito.views.OnInputAddressListener;
import uit.minito.views.OnMainMenuListener;
import uit.minito.views.OnTouchResultNavigatorListener;
import uit.minito.views.ResultNavigator;
import uit.minito.views.Utility;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class Map2MainActivity extends FragmentActivity implements
		OnInputAddressListener, OnTouchResultNavigatorListener,
		OnCustomZoomControlsListener, OnClickListener, OnMainMenuListener {

	InputLayout inputBoard;
	GoogleMap myMapView;
	SupportMapFragment mapFrag;
	CircleButton menuButton;
	Button trackerButton;

	ResultNavigator resultNavigator;
	MainMenu mainMenu;
	LatLng geoStart = null;
	LatLng geoEnd = null;
	int chooseStart = 0;

	LatLng gLongPressLocation;

	HistoryDBAdapter historyAccess;
	Vector<Vector<MyData>> currentDataResult;      

	LocationManager locationManager;
	LocationListener locationListener;
	boolean isFirst = true;
	Marker TrackingMakerOverlay;
	Marker PeopleMakerOverlay;

	ArrayList<MyPoint> arrayTracking;                    

	String allResult = "";      
	int indexArrayResult = 0;    
	int indexResult = 0;
	int color[] = { Color.RED, Color.GREEN, Color.DKGRAY };

	final static int SUBJECT = 0;
	Handler locationHandler = null;

	static boolean isStopTitle = false;
	boolean isGetTrackingMarker = true;
	Drawable trackingDrawable;
	Drawable userDrawable;

	int gLongPressX = 0;
	int gLongPressY = 0;
	QuickAction quickAction;
	QuickAction menuAction;

	boolean isChooseLoc = false;
	boolean isChooseDes = false;
	CustomZoomControls customZoomControl;  
	HistoryModel firstResultHolder = null;

	private void clearPath() {
		for (int i = 0; i < walkingOverlayArr.size(); i++) {
			walkingOverlayArr.get(i).clear();
		}

		for (int i = 0; i < busPathArr.size(); i++) {
			busPathArr.get(i).clear();
		}
	}

	private void createQuickAction() {
		ActionItem startItem = new ActionItem(0, getResources().getString(
				R.string.start_text), getResources().getDrawable(
				R.drawable.flag_start));
		ActionItem endItem = new ActionItem(1, getResources().getString(
				R.string.end_text), getResources().getDrawable(
				R.drawable.flag_end));
		ActionItem closeItem = new ActionItem(2, getResources().getString(
				R.string.menu_clear_all), getResources().getDrawable(
				R.drawable.close));
		quickAction = new QuickAction(this, QuickAction.VERTICAL);
		quickAction.addActionItem(startItem);
		quickAction.addActionItem(endItem);
		quickAction.addActionItem(closeItem);
		quickAction
				.setOnActionItemClickListener(new OnActionItemClickListener() {

					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						stopTracking();
						switch (actionId) {
						case 0:
							clearPath();

							isChooseLoc = true;
							inputBoard.locationField.reset();
							inputBoard.slideDown();
							resultNavigator.hide();
							geoStart = gLongPressLocation;
							new GetAddressTask()
									.execute("http://maps.googleapis.com/maps/api/geocode/json?latlng="
											+ geoStart.latitude
											+ ","
											+ geoStart.longitude
											+ "&sensor=true");
							setLocationMarker("");
							// myMapView.invalidate();
							resultNavigator.reset();
							resultNavigator.hide();

							break;

						case 1:
							clearPath();

							isChooseDes = true;
							inputBoard.destinationField.reset();
							geoEnd = gLongPressLocation;
							new GetAddressTask()
									.execute("http://maps.googleapis.com/maps/api/geocode/json?latlng="
											+ geoEnd.latitude
											+ ","
											+ geoEnd.longitude + "&sensor=true");
							setDestinationMarker("");

							resultNavigator.reset();
							resultNavigator.hide();

							break;
						case 2:

							clearOvelay();
							// myMapView.invalidate();
							geoStart = geoEnd = null;
							inputBoard.clearAllField();
							resultNavigator.reset();
							resultNavigator.hide();
							break;
						}
					}
				});

	}

	private void getControlsFromXML() {
		inputBoard = (InputLayout) findViewById(R.id.inputBoard);

		inputBoard.setOnInputAddressListener(this);
		resultNavigator = (ResultNavigator) findViewById(R.id.resultNavigator);
		customZoomControl = (CustomZoomControls) findViewById(R.id.zoomControl);
		resultNavigator.setOnTouchResultNavigatorListener(this);
		customZoomControl.delegate = this;
		menuButton = (CircleButton) findViewById(R.id.menuButton);
		trackerButton = (Button) findViewById(R.id.trackingButton);
		menuButton.setOnClickListener(this);
		trackerButton.setOnClickListener(this);
		mainMenu = (MainMenu) findViewById(R.id.mainMenu);
		mainMenu.delegate = this;
		
	}

	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.menuButton:
			mainMenu.showOrHide();
			menuButton.autoFade();
			break;

		case R.id.trackingButton:
			break;
		}

	}

	/*
	 * public void setMarker(OverlayItem ov, int imageId, int type) { Drawable
	 * _drawable = getApplicationContext().getResources().getDrawable(imageId);
	 * HelloItemizedOverlay StartMakerOverlay = new
	 * HelloItemizedOverlay(_drawable, Map2MainActivity.this, false); // Set
	 * OverlayItem StartMakerOverlay.setOverlayType(type);
	 * StartMakerOverlay.addOverlay(ov);
	 * myMapView.getOverlays().add(StartMakerOverlay); }
	 */

	Marker StartMakerOverlay;

	public void setLocationMarker(String text) {

		if (StartMakerOverlay != null) {
			StartMakerOverlay.remove();
		}

		StartMakerOverlay = myMapView.addMarker(new MarkerOptions()
				.position(geoStart)
				.title(getResources().getString(R.string.start_text))
				.snippet(text)
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.starticon)));

	}

	Marker EndMakerOverlay;

	public void setDestinationMarker(String text) {

		if (EndMakerOverlay != null) {
			EndMakerOverlay.remove();
		}

		EndMakerOverlay = myMapView
				.addMarker(new MarkerOptions()
						.position(geoEnd)
						.title(getResources().getString(R.string.end_text))
						.snippet(text)
						.icon(BitmapDescriptorFactory
								.fromResource(R.drawable.endicon)));
	}

	private void saveToHistory(SuggestionModel suggestionStart,
			SuggestionModel suggestionEnd) {
		HistoryModel history = new HistoryModel();
		history.setHistoryID(historyAccess.getLastInsertedHistory() + 1);
		history.setLatitudeStart(String.valueOf(suggestionStart.getLatitude()));
		history.setLongitudeStart(String.valueOf(suggestionStart.getLongitude()));
		history.setAddressStart(suggestionStart.getAddress());

		history.setLatitudeEnd(String.valueOf(suggestionEnd.getLatitude()));
		history.setLongitudeEnd(String.valueOf(suggestionEnd.getLongitude()));
		history.setAddressEnd(suggestionEnd.getAddress());

		history.setDateAdded(new java.sql.Date(new Date().getTime()));
		history.setNumOfRouters(firstResultHolder.getNumOfRouters());
		history.setRouterDetails(firstResultHolder.getRouterDetails());
		history.setTimeSpent(firstResultHolder.getTimeSpent());
		history.setDistance(firstResultHolder.getDistance());
		historyAccess.insertHistoryModel(history);
	}

	public void handleIntentFromHistory() {
		Intent intent = getIntent();
		if (intent != null) {
			if (intent.getExtras() != null) {
				HistoryModel history = (HistoryModel) intent
						.getSerializableExtra("history");
				SuggestionModel suggestionStart = new SuggestionModel(
						history.getAddressStart(), Double.parseDouble(history
								.getLatitudeStart()),
						Double.parseDouble(history.getLongitudeStart()));

				SuggestionModel suggestionEnd = new SuggestionModel(
						history.getAddressEnd(), Double.parseDouble(history
								.getLatitudeEnd()), Double.parseDouble(history
								.getLongitudeEnd()));
				inputBoard.locationField.fillWithModel(suggestionStart);
				inputBoard.destinationField.fillWithModel(suggestionEnd);
				inputBoard.beginSearching();
			}

		}
	}

	public void stopTracking() {
		if (locationHandler == null)
			return;
		locationHandler.removeMessages(SUBJECT);
		indexTracking = 0;
		isStopTitle = false;
		/*
		 * myMapView.getOverlays().remove(TrackingMakerOverlay);
		 * myMapView.getOverlays().remove(PeopleMakerOverlay);
		 * myMapView.invalidate();
		 */
	}

	public void setTrackingOverlay() {
		if (TrackingMakerOverlay != null) {
			TrackingMakerOverlay.remove();
		}

		TrackingMakerOverlay = myMapView.addMarker(new MarkerOptions()
				.position(
						new LatLng(arrayTracking.get(indexTracking).getLat(),
								arrayTracking.get(indexTracking).getLng()))
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.trackicon)));
	}

	Marker PeopleMarkerOverlay;
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		customZoomControl.show();
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN: //
			gLongPressX = (int) ev.getRawX();
			gLongPressY = (int) ev.getRawY();
			break;

		case MotionEvent.ACTION_MOVE:
			gLongPressX = (int) ev.getRawX();  
			gLongPressY = (int) ev.getRawY();
			break;
		case MotionEvent.ACTION_UP:
			customZoomControl.runTimer();  
			break;
		}
		
		return super.dispatchTouchEvent(ev);
	}

	public void setPeopleOverlay(LatLng point) {
		if (PeopleMarkerOverlay != null) {
			PeopleMarkerOverlay.remove();
		}

		PeopleMarkerOverlay = myMapView.addMarker(new MarkerOptions().position(
				point).icon(
				BitmapDescriptorFactory.fromResource(R.drawable.people)));
	}

	LatLng HCM = new LatLng(10.770959, 106.699384);

	private SupportMapFragment mMapFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_main);
		getControlsFromXML();
		
		
		
		historyAccess = new HistoryDBAdapter(this);  

		// StrictMode.ThreadPolicy policy = new
		// StrictMode.ThreadPolicy.Builder().permitAll().build();
		// StrictMode.setThreadPolicy(policy);

		mapFrag = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);
		myMapView = mapFrag.getMap();
		// myMapView = ((MapFragment)
		// getFragmentManager().findFragmentById(R.id.map)).getMap();
		myMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(HCM, 14));
		createQuickAction();
		myMapView.getUiSettings().setZoomControlsEnabled(false);

		myMapView
				.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

					public void onMapLongClick(LatLng position) {
						// TODO Auto-generated method stub
						gLongPressLocation = position;

						quickAction.show(gLongPressX, gLongPressY,
								mapFrag.getView());
					}
				});

		

		handleIntentFromHistory();

		// Acquire a reference to the system Location Manager
		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// Define a listener that responds to location updates
		locationListener = new LocationListener() {
			public void onLocationChanged(Location location) {
				if (isFirst == false)
					return;  
  
				if (isGetGPS == true) {
					isChooseLoc = true;
					// myMapView.getOverlays().remove(LocationMakerOverlay);
					geoStart = new LatLng(location.getLatitude(),
							location.getLongitude());    
					new GetAddressTask()  
							.execute("http://maps.googleapis.com/maps/api/geocode/json?latlng="
									+ geoStart.latitude  
									+ ","
									+ geoStart.longitude + "&sensor=true");
					setLocationMarker("");
					myMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(
							geoStart, 12));

					// myMapView.invalidate();
					isGetGPS = false;
				} else {
					trackingBusStation(location);
				}

				isFirst = false;
				locationManager.removeUpdates(locationListener);
			}

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			public void onProviderEnabled(String provider) {
			}

			public void onProviderDisabled(String provider) {
			}
		};

		locationHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == SUBJECT) {
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER, 0, 0,
							locationListener);
					isFirst = true;
					this.sendEmptyMessageDelayed(SUBJECT,
							StaticVariables.TimeTracking);
				}
			}
		};
	}

	void trackingBusStation(Location location) {
		// myMapView.getOverlays().remove(LocationMakerOverlay);
		LatLng gp = new LatLng(location.getLatitude(), location.getLongitude());
		setPeopleOverlay(gp);

		if (isGetTrackingMarker == true) {

			MyPoint userPoint = new MyPoint(location.getLatitude(),
					location.getLongitude());
			double min = getDistanceOfTwoPoint(userPoint, arrayTracking.get(0));
			indexTracking = 0;

			for (int i = 1; i < arrayTracking.size(); i++) {

				if (min > getDistanceOfTwoPoint(userPoint, arrayTracking.get(i))) {
					min = getDistanceOfTwoPoint(userPoint, arrayTracking.get(i));
					indexTracking = i;
				}
			}
			setTrackingOverlay();
			isGetTrackingMarker = false;
		}

		// myMapView.getOverlays().add(PeopleMakerOverlay);
		myMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(gp, 17));

		new GetDistanceTask()
				.execute("http://maps.googleapis.com/maps/api/directions/json?"
						+ "origin="
						+ String.valueOf(location.getLatitude())
						+ ","
						+ String.valueOf(location.getLongitude())
						+ "&destination="
						+ String.valueOf(arrayTracking.get(indexTracking)
								.getLat())
						+ ","
						+ String.valueOf(arrayTracking.get(indexTracking)
								.getLng()) + "&mode=driving&sensor=false");
	}

	int indexTracking = 0;
	boolean isPressTrackButton = true;

	class GetDistanceTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... uri) {

			return Utility.getJsonFromURL(uri[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			if (result == null || result == "") {
				Toast.makeText(getApplicationContext(), "No Info",
						Toast.LENGTH_SHORT).show();
				return;
			}

			JSONObject allResult;
			try {
				allResult = new JSONObject(result);
				int distance = allResult.getJSONArray("routes")
						.getJSONObject(0).getJSONArray("legs").getJSONObject(0)
						.getJSONObject("distance").getInt("value");

				Toast.makeText(
						getApplicationContext(),
						"TrÃ¡ÂºÂ¡m dÃ¡Â»Â«ng tiÃ¡ÂºÂ¿p theo cÃƒÂ²n: "
								+ String.valueOf(distance) + "m",
						Toast.LENGTH_SHORT).show();

				if (distance < StaticVariables.MinDistaceTracking) {

					Vibrator vibe = (Vibrator) getApplicationContext()
							.getSystemService(Context.VIBRATOR_SERVICE);
					vibe.vibrate(4000);

					if (indexTracking < currentDataResult.size() * 2 - 1) {
						if (isPressTrackButton == false)
							return;
						isPressTrackButton = false;
						AlertDialog.Builder builder = new AlertDialog.Builder(
								Map2MainActivity.this);
						builder.setTitle("LÃ†Â°u ÃƒÂ½:")
								.setMessage(
										"CÃƒÂ²n khoÃ¡ÂºÂ£ng "
												+ distance
												+ " m nÃ¡Â»Â¯a lÃƒÂ  tÃ¡Â»â€ºi trÃ¡ÂºÂ¡m dÃ¡Â»Â«ng!")
								.setCancelable(false)
								.setPositiveButton(
										"Track trÃ¡ÂºÂ¡m tiÃ¡ÂºÂ¿p theo",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												indexTracking++;
												setTrackingOverlay();
												isPressTrackButton = true;
											}
										})
								.setNegativeButton("TiÃ¡ÂºÂ¿p tÃ¡Â»Â¥c",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												isPressTrackButton = true;
											}
										});

						AlertDialog alert = builder.create();
						alert.show();
					} else {
						stopTracking();
						AlertDialog.Builder builder = new AlertDialog.Builder(
								Map2MainActivity.this);
						builder.setTitle("ThÃƒÂ´ng bÃƒÂ¡o:")
								.setMessage(
										"BÃ¡ÂºÂ¡n Ã„â€˜ÃƒÂ£ Ã„â€˜Ã¡ÂºÂ¿n trÃ¡ÂºÂ¡m cuÃ¡Â»â€˜i!")
								.setCancelable(false)
								.setPositiveButton("XÃƒÂ¡c nhÃ¡ÂºÂ­n",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {

											}
										});

						AlertDialog alert = builder.create();
						alert.show();
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	public void dismissKeyboard() {
		if (inputBoard.keyBoardIsOnScreen()) {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm.isAcceptingText()) {
				imm.hideSoftInputFromWindow(inputBoard
						.getCurrentFocusEditText().getWindowToken(), 0);
			}
		}
	}

	/*
	 * @Override public boolean onPrepareOptionsMenu(Menu menu) {
	 * 
	 * MenuItem mi = menu.getItem(3); if (isStopTitle == false)
	 * mi.setTitle("Tracking"); else mi.setTitle("Stop");
	 * 
	 * return super.onPrepareOptionsMenu(menu); }
	 */
	Boolean isGetGPS = false;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_history:
			Intent intent = new Intent(Map2MainActivity.this,
					HistoryViewActivity.class);
			startActivity(intent);
			break;
		case R.id.menu_lookup:
			Intent intent2 = new Intent(Map2MainActivity.this,
					RouterViewActivity.class);
			startActivity(intent2);
			break;

		case R.id.menu_gps:
			stopTracking();
			isGetGPS = true;
			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
			isFirst = true;
			break;

		case R.id.menu_tracking:

			if (item.getTitle().equals("Tracking")) {
				Log.i("NND", "Start Tracking");
				if (currentDataResult == null) {
					Toast.makeText(Map2MainActivity.this,
							"ChÃ†Â°a cÃƒÂ³ trÃ¡ÂºÂ¡m dÃ¡Â»Â«ng",
							Toast.LENGTH_SHORT).show();
					break;
				}

				arrayTracking = new ArrayList<MyPoint>();
				indexTracking = 0;

				for (int i = 0; i < currentDataResult.size(); i++) {
					arrayTracking.add(new MyPoint(currentDataResult.get(i)
							.firstElement().getLat(), currentDataResult.get(i)
							.firstElement().getLng()));
					arrayTracking.add(new MyPoint(currentDataResult.get(i)
							.lastElement().getLat(), currentDataResult.get(i)
							.lastElement().getLng()));
				}

				locationHandler.sendEmptyMessage(SUBJECT);
				isGetTrackingMarker = true;
				isStopTitle = true;
			} else {
				Log.i("NND", "Stop Tracking");
				stopTracking();
			}
		}
		return super.onOptionsItemSelected(item);
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
	 * menu; this adds items to the action bar if it is present.
	 * getMenuInflater().inflate(R.menu.activity_main, menu); return true; }
	 */

	public void clearOvelay() {
		myMapView.clear();
	}

	private double sLat, sLng, eLat, eLng;
	public String locField, desField;

	public void search(double startLat, double startLong, double endLat,
			double endLong) {
		sLat = startLat;
		sLng = startLong;
		eLat = endLat;
		eLng = endLong;

		clearOvelay();
		allResult = null;
		indexResult = 0;

		locField = inputBoard.locationField.getText().toString();
		desField = inputBoard.destinationField.getText().toString();

		geoStart = new LatLng(sLat, sLng);
		geoEnd = new LatLng(eLat, eLng);

		setLocationMarker(locField);
		setDestinationMarker(desField);

		new RequestTask().execute(StaticVariables.serverURL
				+ "/MainPage?locLat=" + startLat + "&locLng=" + startLong
				+ "&desLat=" + endLat + "&desLng=" + endLong);

		inputBoard.slideUp();
		// inputBoard.clearAllField();
		dismissKeyboard();
		stopTracking();
	}

	private ProgressDialog pdia;

	class GetAddressTask extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pdia = new ProgressDialog(Map2MainActivity.this);
			pdia.setMessage("Loading...");
			pdia.show();
		}

		@Override
		protected String doInBackground(String... uri) {

			String result = "";
			try {
				String json = Utility.getJsonFromURL(uri[0]);
				if (json == null)
					return "";

				JSONObject arrObj = new JSONObject(json);
				JSONArray arr = arrObj.getJSONArray("results");
				result = arr.getJSONObject(0).getString("formatted_address");

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pdia.dismiss();
			if (result == "")
				Toast.makeText(
						getApplicationContext(),
						"LÃ¡ÂºÂ¥y Ã„â€˜Ã¡Â»â€¹a chÃ¡Â»â€° thÃ¡ÂºÂ¥t bÃ¡ÂºÂ¡i! Vui lÃƒÂ²ng chÃ¡Â»ï¿½n lÃ¡ÂºÂ¡i",
						Toast.LENGTH_SHORT).show();

			if (isChooseLoc == true) {
				inputBoard.locationField.fillWithModel(new SuggestionModel(
						result, geoStart.latitude, geoStart.longitude));
				isChooseLoc = false;
			}

			if (isChooseDes == true) {
				inputBoard.destinationField.fillWithModel(new SuggestionModel(
						result, geoEnd.latitude, geoEnd.longitude));
				isChooseDes = false;
			}
		}
	}

	Vector<DrawPathOverlay> busPathArr = new Vector<DrawPathOverlay>();

	public void nextResult(String result, int index) {

		JSONArray allResultarr;
		ArrayList<String> arrRouter = new ArrayList<String>();

		if (result == null || result == "") {
			Toast.makeText(getApplicationContext(),
					"KhÃƒÂ´ng tÃƒÂ¬m thÃ¡ÂºÂ¥y kÃ¡ÂºÂ¿t quÃ¡ÂºÂ£!",
					Toast.LENGTH_SHORT).show();
			return;
		}

		stopTracking();

		try {

			allResultarr = new JSONArray(result);
			indexArrayResult = allResultarr.length();
			JSONArray currentResult = allResultarr.getJSONArray(index);
			currentDataResult = new Vector<Vector<MyData>>();

			for (int i = 0; i < currentResult.length(); i++) {
				Vector<MyData> dataResult = new Vector<MyData>();

				for (int j = 0; j < currentResult.getJSONArray(i).length(); j++) {
					JSONObject jo = currentResult.getJSONArray(i)
							.getJSONObject(j);
					MyData md;

					if (!jo.has("address")) {
						md = new MyData(jo.getDouble("lat"),
								jo.getDouble("lng"));
					} else {
						md = new MyData(jo.getDouble("lat"),
								jo.getDouble("lng"), jo.getString("routerID"),
								jo.getString("address"));
					}

					if (jo.has("timeResult")) {
						md.setTimeResult(jo.getString("timeResult"));
					}

					if (jo.has("distanceResult")) {
						md.setDistanceResult(jo.getString("distanceResult"));
					}

					dataResult.add(md);
				}
				arrRouter.add(dataResult.get(0).getRouterID());
				currentDataResult.add(dataResult);
			}

			for (int i = 0; i < currentDataResult.size(); i++) {
				DrawPathOverlay dpo = new DrawPathOverlay(myMapView,
						Map2MainActivity.this, currentDataResult.get(i),
						color[i], false);
				dpo.draw();
				busPathArr.add(dpo);
			}

			DecimalFormat df = new DecimalFormat("#.00");
			String distance = df.format(Double.valueOf(currentDataResult.get(0)
					.get(0).getDistanceResult()) / 1000);

			resultNavigator.display();

			String timefromjson = currentDataResult.get(0).get(0)
					.getTimeResult();
			int indexDot = timefromjson.indexOf(".");
			resultNavigator.setInfo(indexArrayResult, indexResult,
					currentDataResult.size(), arrRouter,
					Double.valueOf(distance),
					timefromjson.substring(0, indexDot));

			if (index == 0) {
				firstResultHolder = new HistoryModel();
				firstResultHolder.setNumOfRouters(arrRouter.size());
				ArrayList<Integer> intRouterNameList = MyUtilities
						.convertRouterNameArrayToIntArray(arrRouter);
				String routerDetailsString = "";
				for (int indexOfRouterDetails = 0; indexOfRouterDetails < intRouterNameList
						.size(); indexOfRouterDetails++) {
					routerDetailsString += String.valueOf(intRouterNameList
							.get(indexOfRouterDetails));
					if (indexOfRouterDetails == intRouterNameList.size() - 1) {

					} else {
						routerDetailsString += ",";
					}
				}
				firstResultHolder.setRouterDetails(routerDetailsString);
				firstResultHolder.setTimeSpent(Double.parseDouble(timefromjson
						.substring(0, indexDot)));
				firstResultHolder.setDistance(Double.valueOf(distance));

				saveToHistory(inputBoard.locationField.getCurrentSuggestion(),
						inputBoard.destinationField.getCurrentSuggestion());
			}

			// Set Bound
			Vector<LatLng> arr = new Vector<LatLng>();

			for (int i = 0; i < currentDataResult.size(); i++) {
				LatLng first = currentDataResult.get(i).firstElement()
						.getLatLng();
				LatLng last = currentDataResult.get(i).lastElement()
						.getLatLng();
				arr.add(first);
				arr.add(last);
			}
			arr.add(geoStart);
			arr.add(geoEnd);
			Utility.zoomInBounds(myMapView, arr);

			// DrawWalking Task:
			new DrawWalkingTask().execute();

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class RequestTask extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pdia = new ProgressDialog(Map2MainActivity.this);
			pdia.setMessage("Loading...");
			pdia.show();
		}

		@Override
		protected String doInBackground(String... uri) {

			return Utility.getJsonFromURL(uri[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pdia.dismiss();
			allResult = result;
			nextResult(result, 0);
		}
	}

	Vector<DrawPathOverlay> walkingOverlayArr = new Vector<DrawPathOverlay>();

	class DrawWalkingTask extends
			AsyncTask<String, String, Vector<Vector<LatLng>>> {

		@Override
		protected Vector<Vector<LatLng>> doInBackground(String... uri) {
			// Draw Walking Router:

			Vector<Vector<LatLng>> arr = new Vector<Vector<LatLng>>();

			try {
				Vector<LatLng> route = getWalkingRouter(sLat, sLng,
						currentDataResult.get(0).get(0).getLat(),
						currentDataResult.get(0).get(0).getLng());

				arr.add(route);

				for (int i = 0; i < currentDataResult.size() - 1; i++) {
					Vector<LatLng> route1 = getWalkingRouter(currentDataResult
							.get(i).lastElement().getLat(), currentDataResult
							.get(i).lastElement().getLng(), currentDataResult
							.get(i + 1).get(0).getLat(),
							currentDataResult.get(i + 1).get(0).getLng());

					arr.add(route1);
				}

				Vector<LatLng> route2 = getWalkingRouter(currentDataResult
						.lastElement().lastElement().getLat(),
						currentDataResult.lastElement().lastElement().getLng(),
						eLat, eLng);

				arr.add(route2);

			} catch (Exception e) {

			}

			return arr;
		}

		@Override
		protected void onPostExecute(Vector<Vector<LatLng>> result) {
			super.onPostExecute(result);

			for (int i = 0; i < result.size(); i++) {
				DrawPathOverlay dpo = new DrawPathOverlay(myMapView,
						Map2MainActivity.this, result.get(i), Color.BLUE);
				dpo.draw();
				walkingOverlayArr.add(dpo);
			}
			// myMapView.invalidate();

			Handler myHandler = new Handler();
			myHandler.postDelayed(delayNextThread, 1000);// Me
		}

	}

	Vector<LatLng> getWalkingRouter(double loc1, double loc2, double des1,
			double des2) {
		Vector<LatLng> arrLatLng = new Vector<LatLng>();

		try {
			String json = Utility
					.getJsonFromURL("http://maps.google.com/maps/api/directions/json?origin="
							+ loc1
							+ ","
							+ loc2
							+ "&destination="
							+ des1
							+ ","
							+ des2 + "&sensor=true&mode=walking");
			if (json == null)
				return null;

			JSONObject arrObj = new JSONObject(json);
			JSONArray arr = arrObj.getJSONArray("routes");
			JSONObject op = arr.getJSONObject(0).getJSONObject(
					"overview_polyline");

			arrLatLng = decodePoly(op.getString("points"));

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return arrLatLng;
	}

	private Vector<LatLng> decodePoly(String encoded) {

		Vector<LatLng> poly = new Vector<LatLng>();
		int index = 0, len = encoded.length();
		int lat = 0, lng = 0;

		while (index < len) {
			int b, shift = 0, result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lat += dlat;

			shift = 0;
			result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lng += dlng;

			LatLng p = new LatLng(((double) lat / 1E5), ((double) lng / 1E5));
			poly.add(p);
		}

		return poly;
	}

	private Runnable delayNextThread = new Runnable() {
		public void run() {
			isClickNext = true;
		}
	};

	private boolean isHaveingResult() {
		return allResult != null;
	}

	boolean isClickNext = false;

	public void onTouchPrev() {
		if (isHaveingResult()) {

			if (isClickNext == false)
				return;

			if (indexResult > 0) {
				indexResult--;
			} else {
				indexResult = indexArrayResult - 1;
			}
			clearOvelay();
			setLocationMarker("Ä�iá»ƒm báº¯t Ä‘áº§u:");
			setDestinationMarker("Ä�iá»ƒm káº¿t thÃºc");
			nextResult(allResult, indexResult);
			isClickNext = false;
		}

	}

	public void onTouchNext() {
		if (isHaveingResult()) {

			if (isClickNext == false)
				return;

			if (indexResult < indexArrayResult - 1) {
				indexResult++;
			} else {
				indexResult = 0;
			}

			clearOvelay();
			setLocationMarker("Ä�iá»ƒm báº¯t Ä‘áº§u:");
			setDestinationMarker("Ä�iá»ƒm káº¿t thÃºc");
			nextResult(allResult, indexResult);
			isClickNext = false;
		}

	}

	public void onPressSlideUp() {
		// TODO Auto-generated method stub
		boolean isDisplayingResult = true;
		if (isDisplayingResult) {
			// resultNavigator.display();
		}
	}

	public double getDistanceOfTwoPoint(MyPoint p1, MyPoint p2) {
		double earthRadius = 3958.75;
		double dLat = Math.toRadians(p2.getLat() - p1.getLat());
		double dLng = Math.toRadians(p2.getLng() - p1.getLng());
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
				+ Math.cos(Math.toRadians(p1.getLat()))
				* Math.cos(Math.toRadians(p2.getLat())) * Math.sin(dLng / 2)
				* Math.sin(dLng / 2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		double dist = earthRadius * c;

		int meterConversion = 1609;

		return new Float(dist * meterConversion).floatValue();
	}

	public void onPressSlideDown() {
		// resultNavigator.hide();
	}

	public void onPressSwap() {
		/*
		 * for(int i=0;i<myMapView.getOverlays().size();i++){
		 * 
		 * Overlay iOverlay=(Overlay) myMapView.getOverlays().get(i); if(
		 * iOverlay.getClass() == HelloItemizedOverlay.class){
		 * HelloItemizedOverlay helloOverlay=(HelloItemizedOverlay)iOverlay;
		 * if(helloOverlay.getOverlayType()==0 ||
		 * helloOverlay.getOverlayType()==1){
		 * 
		 * }else{ myMapView.getOverlays().remove(i); i--; } }else{
		 * myMapView.getOverlays().remove(i); i--; } }
		 * 
		 * int iSize=myMapView.getOverlays().size(); for(int i=0;i<iSize;i++){
		 * HelloItemizedOverlay iOverlay=(HelloItemizedOverlay)
		 * myMapView.getOverlays().get(i); OverlayItem iItem=
		 * iOverlay.getItem(0);
		 * 
		 * switch (iOverlay.getOverlayType()) { case 0:
		 * myMapView.getOverlays().remove(i); i--; iSize--; setMarker(iItem,
		 * R.drawable.endicon, 1); break;
		 * 
		 * case 1: myMapView.getOverlays().remove(i); i--; iSize--;
		 * setMarker(iItem, R.drawable.starticon, 0); break; } }
		 * getResources().getString(R.string.end_text), ""), // false);
		 * getResources().getString(R.string.start_text), ""), // false);
		 */
		clearOvelay();
		LatLng temp = geoStart;
		geoStart = geoEnd;
		geoEnd = temp;

		setLocationMarker("");
		setDestinationMarker("");

		resultNavigator.reset();
		resultNavigator.hide();

	}

	public void onPressZoomingIn() {
		myMapView.animateCamera(CameraUpdateFactory.zoomIn());
	}

	public void onPressZoomingOut() {
		myMapView.animateCamera(CameraUpdateFactory.zoomOut());
	}

	public void onTouchRouter() {
		// TODO Auto-generated method stub
		Intent intent2 = new Intent(Map2MainActivity.this,
				RouterViewActivity.class);
		startActivity(intent2);
		mainMenu.hide();
		menuButton.fadeOut();
	}

	public void onTouchHistory() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(Map2MainActivity.this,
				HistoryViewActivity.class);
		startActivity(intent);
		mainMenu.hide();
		menuButton.fadeOut();
	}

	public void onTouchSettings() {
		// TODO Auto-generated method stub

	}

	public void onTouchFeedback() {
		// TODO Auto-generated method stub

	}

}
